﻿using System;
using System.Data;
using BP.DA;
using BP.Port;
using BP.En;
using BP.Web;
using BP.WF.Template;
using BP.Sys;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using DocumentFormat.OpenXml.Bibliography;
using NPOI.SS.Formula.Functions;
using System.Drawing;
using Ubiety.Dns.Core.Common;
using System.Collections;
using DocumentFormat.OpenXml.Drawing;
using System.Text.Json.Nodes;

namespace BP.Demo
{
    /// <summary>
    /// 下载股票数据 的摘要说明
    /// </summary>
    public class DTS_Stock : Method
    {
        /// <summary>
        /// 下载股票数据
        /// </summary>
        public DTS_Stock()
        {
            this.Title = "下载股票数据到Demo_Track";
            this.Help = "可以不定期的手工执行,获取最近三个月的数据，存储到Demo_Trade表里.";
            this.GroupName = "系统演示";
        }
        /// <summary>
        /// 设置执行变量
        /// </summary>
        /// <returns></returns>
        public override void Init()
        {
        }
        /// <summary>
        /// 当前的操纵员是否可以执行这个方法
        /// </summary>
        public override bool IsCanDo
        {
            get
            {
                return true;
            }
        }
        /// <summary>
        /// 执行
        /// </summary>
        /// <returns>返回执行结果</returns>
        public override object Do()
        {
            string msg = "";
            Stocks ens = new Stocks();
            ens.RetrieveAll();
            foreach (Stock en in ens)
            {
               msg+= en.DTS_CurrData();
               msg+= en.DTS_Stock();
            }
            return "执行成功:" + msg;
        }

        public string GenerCurrData(Stock stock)
        {
            SFSearch search = new SFSearch("StockCode");

            Hashtable ht = new Hashtable();

            string secid = GenerateSecId(stock.No);

            ht.Add("location", secid);

            DataTable dataTable = search.GenerHisDataTable(ht);

            DataTable dt = BP.Tools.Json.ToDataTable(dataTable.Rows[0][2].ToString());

            stock.SetValByKey("DT", DataType.CurrentDateByFormart("yyyy-MM-dd") ); //时间
            // 提取字段

            double high = Convert.ToDouble(dt.Rows[0]["f44"]);  // 最高价
            double low = Convert.ToDouble(dt.Rows[0]["f45"]);   // 最低价
            double prevClose = Convert.ToDouble(dt.Rows[0]["f60"]); // 昨收价
            // 计算振幅
            double amplitude = (high - low) / prevClose * 100;

            stock.SetValByKey("OpenNum", dt.Rows[0]["f46"] ); //开盘价.
            stock.SetValByKey("MaxNum", high); //最高.
            stock.SetValByKey("MinNum", low); //最低.
            stock.SetValByKey("SwingNum", amplitude); //振幅.
            stock.SetValByKey("CloseNum", prevClose); //收盘价.
            stock.Update();

            return "股票：" + stock.No + "获取到了当前最新数据"; 
        }
        /// <summary>
        /// 生成数据
        /// </summary>
        /// <param name="stockNo">股票编号</param>
        /// <param name="stockShortNo">短号</param>
        public string GenerHistoryData(string stockNo, string year)
        {
            string secid = GenerateSecId(stockNo);
            string begDate = $"{year}0101";
            string endDate = $"{year}1231";
            SFSearch search = new SFSearch("StockHistory");
            Hashtable ht = new Hashtable();
            ht.Add("secid", secid);
            ht.Add("begDate", begDate);
            ht.Add("endDate", endDate);
            DataTable dt = search.GenerHisDataTable(ht);

            int numInsert = 0;
            int numUpdate = 0;
            int total = 0;
            object cellValue = dt.Rows[0][2];
            object datavalue = cellValue.ToString().Replace("[", "").Replace("]", "").Replace("\r\n", "").Trim().Split("\",");
            if (datavalue is string[] stringArray)
            {
                total = stringArray.Length;
                foreach (string kline in stringArray)
                {
                    string[] fields = kline.Replace("\"", "").Trim().Split(',');

                    if (fields.Length >= 11)
                    {
                        string data = fields[0];
                        BP.Demo.Trade td = new Trade();
                        td.No = stockNo + "_" + data;
                        if (td.RetrieveFromDBSources() == 0)
                        {
                            td.StockNo = stockNo;
                            td.Name = data;
                            td.MaxNum = decimal.Parse(fields[3]); //最高金额
                            td.MinNum = decimal.Parse(fields[4]); //最低金额
                            td.CloseNum = decimal.Parse(fields[2]); //收盘价
                            td.SwingNum = decimal.Parse(fields[7]); //振幅金额(路宽)
                            td.Insert();
                            numInsert++;
                        }
                        else
                        {
                            td.StockNo = stockNo;
                            td.Name = data;
                            td.MaxNum = decimal.Parse(fields[3]); //最高金额
                            td.MinNum = decimal.Parse(fields[4]); //最低金额
                            td.CloseNum = decimal.Parse(fields[2]); //收盘价
                            td.SwingNum = decimal.Parse(fields[7]); //振幅金额(路宽)
                            td.Update();
                            numUpdate++;
                        }
                    }
                }
            }
            return "股票：" + stockNo + ",获取到了:" + total + "笔数据,更新:[" + numUpdate + "],插入[" + numInsert + "]";
        }
        public enum StockMarket
        {
            Shanghai = 1,  // 沪市
            Shenzhen = 0   // 深市/北交所
        }
        private string GenerateSecId(string stockCode)
        {
            StockMarket market = stockCode switch
            {
                string s when s.StartsWith("60") || s.StartsWith("68") || s.StartsWith("788")
                    => StockMarket.Shanghai,
                string s when s.StartsWith("00") || s.StartsWith("30") ||
                             s.StartsWith("43") || s.StartsWith("83") || s.StartsWith("87")
                    => StockMarket.Shenzhen,
                _ => throw new ArgumentException("不支持的股票代码格式")
            };

            return $"{(int)market}.{stockCode}";
        }
    }
}
